import re
import logging

from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin

from utils.JwtUtil import verify_token

# 导入你自己的 JWT 工具类


logger = logging.getLogger(__name__)

# 允许的源
ALLOWED_ORIGINS = [
    "http://localhost:5173",  # 前端地址
    "http://localhost:5200",  # 管理后台地址
]

# 不需要鉴权的路径（静态配置）
EXCLUDE_PATHS = {
    '/api/user/login/',
    '/api/user/register/',
    '/api/admin/login/',
}

# 使用正则表达式跳过某些路径
EXCLUDE_PATH_REGEXES = [
    r'^/api/users/',  # 所有 /api/user/ 开头的路径都放行
    r'^/api/admin/login',  # 管理员登录也放行
]


class JwtAuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        origin = request.META.get('HTTP_ORIGIN')
        request.allowed_origin = origin if origin in ALLOWED_ORIGINS else None

        # 处理 OPTIONS 预检请求
        if request.method == 'OPTIONS':
            response = JsonResponse({'detail': 'OK'}, status=200)
            self.add_cors_headers(response, origin)
            return response

        path = request.path_info.rstrip('/')

        # 跳过不需要 token 的路径
        if path in [p.rstrip('/') for p in EXCLUDE_PATHS]:
            logger.warning("该路径无需 Token，放行")
            return None

        # 正则匹配跳过路径
        for pattern in EXCLUDE_PATH_REGEXES:
            if re.match(pattern, path):
                logger.warning(f"正则匹配成功，路径 {path} 放行")
                return None

        # 忽略静态资源和 media
        if re.match(r'^/(static|media)/', path):
            logger.warning(f"静态资源路径，放行")
            return None

        # 提取 Token
        auth_header = request.headers.get('Authorization')

        if not auth_header or not auth_header.startswith('Bearer '):
            logger.warning("Token 缺失或格式错误")
            return JsonResponse({'error': '登录信息失效，请重新登录',"code":401}, status=401)

        token = auth_header.split(" ", 1)[1].strip()
        logger.info(f"获取到的 token: {token}")

        # ✅ 使用你封装好的 verify_token 方法来验证 token
        payload = verify_token(token)
        if not payload:
            logger.warning("Token 校验失败（可能已过期或无效）")
            return JsonResponse({'error': '登录信息已过期或无效',"code":401}, status=401)

        logger.info(f"解析到用户信息: {payload}")

        # 将用户信息附加到 request 对象中
        request.user_id = payload.get('user_id')
        request.userName = payload.get('userName')  # 注意字段名是否一致
        request.user_role = payload.get('role')  # 如果你在 payload 中没有 role 字段，请注意

        return None  # 继续执行后续逻辑

    def process_response(self, request, response):
        origin = getattr(request, 'allowed_origin', None)
        self.add_cors_headers(response, origin)
        return response

    def add_cors_headers(self, response, origin):
        if origin:
            response['Access-Control-Allow-Origin'] = origin
            response['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
            response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
            response['Access-Control-Allow-Credentials'] = 'true'